//
//  RootTabBarController.m
//  BESTKEEP-OC
//
//  Created by 毛韶谦 on 2016/10/26.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "RootTabBarController.h"
#import "RootNavigationController.h"
#import "Mediator+BKMain.h"
#import "Mediator+BKClassify.h"
#import "Mediator+BKSC.h"
#import "Mediator+BKMy.h"
#import <UIKit/UIKit.h>

#define RootTabBarItemBadgeRadius 7.5f

@interface RootTabBarItem : UITabBarItem

@end

@implementation RootTabBarItem {
    @private
    NSString *_rootTabBarBadgeValue;
    UILabel *_rootTabBarBadgeLabel;
}

-(NSString *)badgeValue {
    return _rootTabBarBadgeValue;
}

-(void)setBadgeValue:(NSString *)badgeValue {
    _rootTabBarBadgeValue = badgeValue;
    [self updateBadgeViewLayout];
}

-(void)updateBadgeViewLayout {
    
    NSString *viewKey = @"view";
    
    if(![Common isVariableWithClass:[UITabBarItem class] varName:viewKey]) {
        return;
    }
    
    UIView *view = [self valueForKey:viewKey];
    if(!view) {
        return;
    }
    
    if(!_rootTabBarBadgeLabel) {
        _rootTabBarBadgeLabel = [[UILabel alloc] init];
        _rootTabBarBadgeLabel.backgroundColor = [UIColor redColor];
        _rootTabBarBadgeLabel.textColor = [UIColor whiteColor];
        _rootTabBarBadgeLabel.textAlignment = NSTextAlignmentCenter;
        _rootTabBarBadgeLabel.font = [UIFont systemFontOfSize:9];
        _rootTabBarBadgeLabel.layer.masksToBounds = YES;
        _rootTabBarBadgeLabel.layer.cornerRadius = RootTabBarItemBadgeRadius;
        if(view.superview) {
            [view.superview addSubview:_rootTabBarBadgeLabel];
        }
    }
    
    BOOL isHiden = _rootTabBarBadgeValue ? NO : YES;
    _rootTabBarBadgeLabel.hidden = isHiden;
    
    if(!isHiden) {
        _rootTabBarBadgeLabel.text = _rootTabBarBadgeValue;
        CGFloat minX = CGRectGetMinX(view.frame) + CGRectGetWidth(view.frame) / 2 + self.imageInsets.left + RootTabBarItemBadgeRadius;
        CGRect frame = CGRectMake(minX, 4, RootTabBarItemBadgeRadius * 2, RootTabBarItemBadgeRadius * 2);
        _rootTabBarBadgeLabel.frame = frame;
    }
}

@end




@interface RootTabBarController ()<UITabBarControllerDelegate>

@end

@implementation RootTabBarController

-(void)viewDidLoad {
    [super viewDidLoad];
    
    [self _initializeComponent];
}

-(void)_initializeComponent {
    
    self.tabBar.tintColor = RGBCOLOR(136, 136, 136, 1);
    NSMutableDictionary *selectTextAttrs = [NSMutableDictionary dictionary];
    selectTextAttrs[NSForegroundColorAttributeName] = RGBCOLOR(3, 181, 152, 1);

    self.delegate = self;
    
    Mediator *mediator = [Mediator sharedInstance];
    
    UIViewController *mainController = [mediator BKMain_mainViewController];
    mainController.tabBarItem = [[RootTabBarItem alloc] init];
    mainController.tabBarItem.image = [self imageOriginal:@"TabBarMain"];
    mainController.tabBarItem.selectedImage = [self imageOriginal:@"TabBarMainSelected"];
    [mainController.tabBarItem setTitleTextAttributes:selectTextAttrs forState:UIControlStateSelected];
    mainController.tabBarItem.title = NSLocalizedString(@"TabBarNewMainTitle", nil);
    RootNavigationController *mainNavigationController = [[RootNavigationController alloc] initWithRootViewController:mainController];
    
    UIViewController *classifyController = [mediator BKClassify_classifyViewController];
    classifyController.tabBarItem = [[RootTabBarItem alloc] init];
    classifyController.tabBarItem.image = [self imageOriginal:@"TabBarClassify"];
    classifyController.tabBarItem.selectedImage = [self imageOriginal:@"TabBarClassifySelected"];
    [classifyController.tabBarItem setTitleTextAttributes:selectTextAttrs forState:UIControlStateSelected];
    [classifyController.tabBarItem setImageInsets:UIEdgeInsetsMake(0, 1, 0, -1)];
    classifyController.tabBarItem.title = NSLocalizedString(@"TabBarNewClassifyTitle", nil);
    RootNavigationController *classifyNavigationController = [[RootNavigationController alloc] initWithRootViewController:classifyController];
    
    UIViewController *shoppingCarController = [mediator BKSC_shoppingCarViewController];
    shoppingCarController.tabBarItem = [[RootTabBarItem alloc] init];
    shoppingCarController.tabBarItem.image = [self imageOriginal:@"TabBarShoppingCar"];
    shoppingCarController.tabBarItem.selectedImage = [self imageOriginal:@"TabBarShoppingCarSelected"];
    [shoppingCarController.tabBarItem setTitleTextAttributes:selectTextAttrs forState:UIControlStateSelected];
    shoppingCarController.tabBarItem.title = NSLocalizedString(@"TabBarNewShoppingCarTitle", nil);
    [shoppingCarController.tabBarItem setImageInsets:UIEdgeInsetsMake(-2, -4, 2, 4)];
    RootNavigationController *shoppingCarNavigationController = [[RootNavigationController alloc] initWithRootViewController:shoppingCarController];
    
    UIViewController *myController = [mediator BKMy_myViewController];
    myController.tabBarItem = [[RootTabBarItem alloc] init];
    myController.tabBarItem.image = [self imageOriginal:@"TabBarMy"];
    myController.tabBarItem.selectedImage = [self imageOriginal:@"TabBarMySelected"];
    [myController.tabBarItem setTitleTextAttributes:selectTextAttrs forState:UIControlStateSelected];
    myController.tabBarItem.title = NSLocalizedString(@"TabBarNewMyTitle", nil);
    RootNavigationController *myNavigationController = [[RootNavigationController alloc] initWithRootViewController:myController];
    
    [self setViewControllers:@[mainNavigationController, classifyNavigationController, shoppingCarNavigationController, myNavigationController]];
    
    for (UIViewController *controller in self.viewControllers) {
        [controller.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: self.tabBar.tintColor} forState:UIControlStateNormal];
    }
    
    [self refreshShoppingCar];
    
    //UIApplicationWillEnterForegroundNotification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForegroundNotification:) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidLoginNotification:) name:UserDidLoginNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidLogoutNotification:) name:UserDidLogoutNotification object:nil];
    
    
}

-(UIImage*)imageOriginal:(NSString*)name {
    UIImage *image = [[UIImage imageNamed:name] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    return image;
}

#pragma -mark UIApplicationWillEnterForegroundNotification
-(void)applicationWillEnterForegroundNotification:(NSNotification*)notification {
    [self refreshShoppingCar];
}

#pragma -mark UserDidLoginNotification
-(void)userDidLoginNotification:(NSNotification*)notification {
    [self refreshShoppingCar];
}

-(void)userDidLogoutNotification:(NSNotification*)notification {
    [self refreshShoppingCar];
}

#pragma -mark shoppingCar
-(void)refreshShoppingCar {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[Mediator sharedInstance] BKSC_getScAmount:^(NSString *amount) {
            NSLog(@"更新购物车数量：%@", amount);
            NSInteger value = [amount integerValue];
            if(value > 0) {
                self.tabBar.items[2].badgeValue = [NSString stringWithFormat:@"%@", amount];
            } else {
                self.tabBar.items[2].badgeValue = nil;
            }
        }];
    });
}

-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    
    UIViewController *currentController = tabBarController.selectedViewController;
    UIViewController *firstController = tabBarController.viewControllers.firstObject;
    //当前选中第一页   并且  在此再次选中第一页
    if([firstController isEqual:currentController] && [firstController isEqual:viewController]) {
        //首页刷新
        [[Mediator sharedInstance] BKMain_refreshData];
    }
    
    return YES;
}

#pragma -mark Autorotate

-(BOOL)shouldAutorotate {
    
//    return self.viewControllers.lastObject.shouldAutorotate;
    return NO;
}

-(UIInterfaceOrientationMask)supportedInterfaceOrientations {
    
//    return self.viewControllers.lastObject.supportedInterfaceOrientations;
    return UIInterfaceOrientationMaskPortrait;
}

-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    
//    return self.viewControllers.lastObject.preferredInterfaceOrientationForPresentation;
    return UIInterfaceOrientationPortrait;
}

#pragma -mark dealloc 
-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
